"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Plus, Edit, Trash2, Download, ArrowUpDown, Upload, ChevronLeft, ChevronRight } from "lucide-react"

interface Template {
  id: string
  name: string
  project: string
  creator: string
  createTime: string
  description: string
  placeholderCount: number
  referenceCount: number
}

export default function TemplateManagement() {
  // 按创建时间倒序排列
  const [templates] = useState<Template[]>([
    {
      id: "1",
      name: "月度财务报告模板",
      project: "财务报告项目",
      creator: "张三",
      createTime: "2024-01-15", // 最近的日期
      description: "标准月度财务报告模板，包含收入、支出、利润等关键指标",
      placeholderCount: 12,
      referenceCount: 5,
    },
    {
      id: "2",
      name: "市场分析报告模板",
      project: "市场分析项目",
      creator: "李四",
      createTime: "2024-01-10", // 第二近的日期
      description: "市场趋势分析模板，包含竞品分析和市场预测",
      placeholderCount: 8,
      referenceCount: 3,
    },
    {
      id: "3",
      name: "员工绩效评估模板",
      project: "人事管理项目",
      creator: "王五",
      createTime: "2024-01-05", // 第三近的日期
      description: "员工季度绩效评估报告模板",
      placeholderCount: 15,
      referenceCount: 7,
    },
  ])

  const [isUploadDialogOpen, setIsUploadDialogOpen] = useState(false)
  const [isDetailDialogOpen, setIsDetailDialogOpen] = useState(false)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null)

  // 分页状态
  const [currentPage, setCurrentPage] = useState(1)
  const [itemsPerPage] = useState(10)
  const totalPages = Math.ceil(templates.length / itemsPerPage)

  const handleViewDetail = (template: Template) => {
    setSelectedTemplate(template)
    setIsDetailDialogOpen(true)
  }

  const handleEdit = (template: Template) => {
    setSelectedTemplate(template)
    setIsEditDialogOpen(true)
  }

  const handleSaveEdit = () => {
    // 保存编辑逻辑
    setIsEditDialogOpen(false)
  }

  // Define placeholder variables
  const 公司名称 = "{{公司名称}}"
  const 报告日期 = "{{报告日期}}"
  const 总收入 = "{{总收入}}"
  const 总支出 = "{{总支出}}"
  const 净利润 = "{{净利润}}"

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">模板管理</h1>
        <Button onClick={() => setIsUploadDialogOpen(true)}>
          <Plus className="h-4 w-4 mr-2" />
          新增模板
        </Button>
      </div>

      <div className="border rounded-lg">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="cursor-pointer">
                模板名称 <ArrowUpDown className="h-4 w-4 inline ml-1" />
              </TableHead>
              <TableHead className="cursor-pointer">
                所属项目 <ArrowUpDown className="h-4 w-4 inline ml-1" />
              </TableHead>
              <TableHead className="cursor-pointer">
                创建人 <ArrowUpDown className="h-4 w-4 inline ml-1" />
              </TableHead>
              <TableHead className="cursor-pointer">
                创建时间 <ArrowUpDown className="h-4 w-4 inline ml-1" />
              </TableHead>
              <TableHead>模板描述</TableHead>
              <TableHead className="cursor-pointer">
                占位符数量 <ArrowUpDown className="h-4 w-4 inline ml-1" />
              </TableHead>
              <TableHead className="cursor-pointer">
                被引用次数 <ArrowUpDown className="h-4 w-4 inline ml-1" />
              </TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {templates.map((template) => (
              <TableRow key={template.id}>
                <TableCell>
                  <Button
                    variant="link"
                    className="p-0 h-auto text-blue-600 font-medium"
                    onClick={() => handleViewDetail(template)}
                  >
                    {template.name}
                  </Button>
                </TableCell>
                <TableCell>{template.project}</TableCell>
                <TableCell>{template.creator}</TableCell>
                <TableCell>{template.createTime}</TableCell>
                <TableCell className="max-w-xs truncate">{template.description}</TableCell>
                <TableCell>
                  <Badge variant="secondary">{template.placeholderCount}</Badge>
                </TableCell>
                <TableCell>
                  <Badge variant="outline">{template.referenceCount}</Badge>
                </TableCell>
                <TableCell>
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" onClick={() => handleEdit(template)}>
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button variant="outline" size="sm">
                      <Download className="h-4 w-4" />
                    </Button>
                    <Button variant="outline" size="sm">
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>

        {/* 分页器 */}
        <div className="flex items-center justify-center py-4 border-t">
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
              disabled={currentPage === 1}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <span className="text-sm">
              第 {currentPage} 页，共 {totalPages} 页
            </span>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setCurrentPage((prev) => Math.min(prev + 1, totalPages))}
              disabled={currentPage === totalPages}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </div>

      {/* 上传模板对话框 */}
      <Dialog open={isUploadDialogOpen} onOpenChange={setIsUploadDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>新增模板</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label htmlFor="templateName">模板名称</Label>
              <Input id="templateName" placeholder="请输入模板名称" />
            </div>
            <div>
              <Label htmlFor="templateDesc">模板描述</Label>
              <Textarea id="templateDesc" placeholder="请输入模板描述" />
            </div>
            <div>
              <Label>上传模板文件</Label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
                <Upload className="h-8 w-8 mx-auto mb-2 text-gray-400" />
                <p className="text-sm text-gray-600">点击上传或拖拽Word文档到此处</p>
                <p className="text-xs text-gray-400 mt-1">支持 .docx, .doc 格式</p>
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setIsUploadDialogOpen(false)}>
                取消
              </Button>
              <Button>上传</Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 模板详情对话框 */}
      <Dialog open={isDetailDialogOpen} onOpenChange={setIsDetailDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>模板详情 - {selectedTemplate?.name}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>所属项目</Label>
                <p className="text-sm text-gray-600">{selectedTemplate?.project}</p>
              </div>
              <div>
                <Label>创建人</Label>
                <p className="text-sm text-gray-600">{selectedTemplate?.creator}</p>
              </div>
              <div>
                <Label>创建时间</Label>
                <p className="text-sm text-gray-600">{selectedTemplate?.createTime}</p>
              </div>
              <div>
                <Label>占位符数量</Label>
                <p className="text-sm text-gray-600">{selectedTemplate?.placeholderCount}</p>
              </div>
            </div>
            <div>
              <Label>模板描述</Label>
              <p className="text-sm text-gray-600">{selectedTemplate?.description}</p>
            </div>
            <div>
              <Label>占位符列表</Label>
              <div className="border rounded p-3 max-h-32 overflow-y-auto">
                <div className="flex flex-wrap gap-2">
                  <Badge variant="outline">{公司名称}</Badge>
                  <Badge variant="outline">{报告日期}</Badge>
                  <Badge variant="outline">{总收入}</Badge>
                  <Badge variant="outline">{总支出}</Badge>
                  <Badge variant="outline">{净利润}</Badge>
                </div>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 编辑模板对话框 */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>编辑模板 - {selectedTemplate?.name}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label htmlFor="editTemplateName">模板名称</Label>
              <Input id="editTemplateName" defaultValue={selectedTemplate?.name} />
            </div>
            <div>
              <Label htmlFor="editTemplateDesc">模板描述</Label>
              <Textarea id="editTemplateDesc" defaultValue={selectedTemplate?.description} />
            </div>
            <div>
              <Label>模板内容</Label>
              <div className="border rounded-lg p-4 h-64 overflow-y-auto">
                <div className="prose max-w-none">
                  <h1>模板内容编辑区</h1>
                  <p>这里是模板内容，可以进行编辑。</p>
                  <p>
                    占位符示例: {公司名称}, {报告日期}, {总收入}
                  </p>
                  <h2>财务报表</h2>
                  <table className="border-collapse border w-full">
                    <thead>
                      <tr>
                        <th className="border p-2">项目</th>
                        <th className="border p-2">金额</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td className="border p-2">总收入</td>
                        <td className="border p-2">{总收入}</td>
                      </tr>
                      <tr>
                        <td className="border p-2">总支出</td>
                        <td className="border p-2">{总支出}</td>
                      </tr>
                      <tr>
                        <td className="border p-2">净利润</td>
                        <td className="border p-2">{净利润}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
            <div>
              <Label>重新上传模板文件</Label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
                <Upload className="h-6 w-6 mx-auto mb-1 text-gray-400" />
                <p className="text-xs text-gray-600">点击上传或拖拽Word文档到此处</p>
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>
                取消
              </Button>
              <Button onClick={handleSaveEdit}>保存</Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}
